package ltd.jdsoft.cute.common.store;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 简易的数据缓存仓库，直接存放堆中
 * 
 * @author zhengzhq
 *
 */
public class SimpleDataStore {

  // 扩展节点的key
  public static final String EXTENTION_LOADER = "EXTENTION_LOADER";
  // 带有参数对扩展节点key
  public static final String EXTENSION_LOADER_WITH_PARAM = "EXTENSION_LOADER_WITH_PARAM";

  // <componentName, <数据名, 数据值>
  private static ConcurrentMap<String, ConcurrentMap<String, Object>> DATA_STORE =
      new ConcurrentHashMap<String, ConcurrentMap<String, Object>>();

  public static boolean contains(String componentName) {
    return DATA_STORE.containsKey(componentName);
  }

  public static boolean contains(String componentName, String storeKey) {
    if (!DATA_STORE.containsKey(componentName)) {
      return false;
    }

    return DATA_STORE.get(componentName).containsKey(storeKey);
  }

  public static Object get(String componentName, String key) {
    if (!DATA_STORE.containsKey(componentName)) {
      return null;
    }
    return DATA_STORE.get(componentName).get(key);
  }

  public static void put(String componentName, String key, Object value) {
    Map<String, Object> componentData = putIfEmpty(componentName);
    componentData.put(key, value);
  }

  private static Map<String, Object> putIfEmpty(String componentName) {
    Map<String, Object> componentData = DATA_STORE.get(componentName);
    if (null == componentData) {
      DATA_STORE.putIfAbsent(componentName, new ConcurrentHashMap<String, Object>());
    }

    return DATA_STORE.get(componentName);
  }

  public static void remove(String componentName, String key) {
    if (!DATA_STORE.containsKey(componentName)) {
      return;
    }
    DATA_STORE.get(componentName).remove(key);
  }

  public static void remove(String componentName) {
    if (!DATA_STORE.containsKey(componentName)) {
      return;
    }

    DATA_STORE.remove(componentName);
  }

  public static void clear(String componentName) {
    if (!DATA_STORE.containsKey(componentName)) {
      return;
    }

    DATA_STORE.get(componentName).clear();
  }
}
